package com.xingxuecn.limit.dao.impl;

import com.xingxuecn.limit.common.model.Role;
import com.xingxuecn.limit.common.model.UserRole;
import com.xingxuecn.limit.common.utils.DbUtils;
import com.xingxuecn.limit.dao.UserRoleDao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author TB at 2018-09-18 10:00
 */
public class UserRoleDaoImpl implements UserRoleDao {
    QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());
    @Override
    public int add(UserRole userRole) throws SQLException {
        String sql = "insert into user_role(user_id,role_id) values(?,?)";
        return queryRunner.execute(sql, new Object[]{
                userRole.getRole_id(),
                userRole.getUser_id()
        });
    }

    @Override
    public int delete(UserRole userRole) throws SQLException {
        String sql = "delete from user_role where user_id = ? and role_id = ?";
        return queryRunner.execute(sql, new Object[]{
                userRole.getRole_id(),
                userRole.getUser_id()
        });
    }

    @Override
    public List<Role> loadRoleByUser(Integer userId) throws SQLException {
        String sql = "select r.* from role r inner join user_role ur on ur.role_id = r.id where ur.user_id = ?";
        return queryRunner.query(sql,new BeanListHandler<Role>(Role.class),new Object[]{userId});
    }

}
